﻿namespace S4sme.Web.Infrastructure.Globalisation
{
    using System.Collections.Specialized;
    using System.Linq;
    using System.Web.Mvc;
    using System.Web.Routing;

    public static class GlobalisationHtmlHelperExtensions
    {
        /* Note: this method can be used to create globalised anchor
        public static MvcHtmlString GlobalisedRouteLink(this HtmlHelper htmlHelper, string linkText, string targetCultureName, RouteData routeData)
        {
            var globalisedRouteData = new RouteValueDictionary { { GlobalisedRoute.CultureKey, targetCultureName } };
            AddRouteValues(routeData, globalisedRouteData);
            return htmlHelper.RouteLink(linkText, globalisedRouteData);
        }*/

        public static string GlobalisedRouteUrl(this UrlHelper urlHelper, string targetCultureName, RouteData routeData, NameValueCollection queryString)
        {
            var globalisedRouteData = new RouteValueDictionary { { GlobalisedRoute.CultureKey, targetCultureName } };
            AddRouteValues(routeData, globalisedRouteData);
            AddQueryStringValues(globalisedRouteData, queryString);
            
            return urlHelper.RouteUrl(globalisedRouteData);
        }

        private static void AddRouteValues(RouteData routeData, RouteValueDictionary destinationRoute)
        {
            foreach (var routeInformation in
                routeData.Values.Where(routeInformation => routeInformation.Key != GlobalisedRoute.CultureKey))
            {
                destinationRoute.Add(routeInformation.Key, routeInformation.Value);
            }
        }

        private static void AddQueryStringValues(RouteValueDictionary destinationRoute, NameValueCollection queryString)
        {
            foreach (string key in queryString.Keys)
            {
                destinationRoute[key] = queryString[key];
            }
        }
    }
}
